package com.swj.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.swj.reggie.common.R;
import com.swj.reggie.dto.DishDto;
import com.swj.reggie.dto.SetmealDto;
import com.swj.reggie.entity.Category;
import com.swj.reggie.entity.Dish;
import com.swj.reggie.entity.Setmeal;
import com.swj.reggie.service.CategoryService;
import com.swj.reggie.service.SetmealDishService;
import com.swj.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CacheManager cacheManager;

    /**
     * 新增套餐，套餐 + 所涉及的菜品
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true) //清除setmealCache名称下,所有的缓存数据
    public R<String> save(@RequestBody SetmealDto setmealDto){
//        log.info("套餐信息：{}",setmealDto);

        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        //分页构造器对象
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据name进行like模糊查询
        queryWrapper.like(name != null,Setmeal::getName,name);
        //添加排序条件，根据更新时间降序排列
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo,queryWrapper);

// "records":[{"id":"1644979857910747137","categoryId":"1413386191767674881","name":"儿童套餐A"...},{...}] 没有categoryName，前端显示有问题
        //SELECT id,category_id,name,price,status... FROM setmeal ORDER BY update_time DESC LIMIT ?
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> dtoPageRecords = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item,setmealDto);  // SetmealDto继承了Setmeal，SetmealDto = Setmeal + categoryName
            //分类id
            Long categoryId = item.getCategoryId();
            //根据分类id查询分类对象，SELECT id,type,name... FROM category WHERE id=?
            Category category = categoryService.getById(categoryId);
            if(category != null){
                //分类名称  categoryName
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        Page<SetmealDto> dtoPage = new Page<>();
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        dtoPage.setRecords(dtoPageRecords);
        return R.success(dtoPage);
    }


    /**
     * 删除套餐，套餐菜品关系表setmeal_dish里的相关数据也要删除
     * 请求方式  DELETE  请求路径  /setmeal  请求参数  ?ids=1423640210125656065,1423338765002256385
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true) //清除setmealCache名称下,所有的缓存数据
    public R<String> delete(@RequestParam List<Long> ids){
//        log.info("ids:{}",ids);

        setmealService.removeWithDish(ids);

        return R.success("套餐数据删除成功");
    }

    /**
     * 套餐的启售、停售
     url       http://localhost:8080/setmeal/status/0
     请求体     ids=1413384757047271425   批量 ids=1644680319266308097,1413384757047271425
     请求方式   post
      status 0停售 1起售     update dish set status=${status} where id in ids
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> update(@PathVariable Integer status,@RequestParam List<Long> ids){
        LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Setmeal::getId, ids).set(Setmeal::getStatus, status);
        setmealService.update(null, updateWrapper);
        return R.success("修改售卖状态成功");
    }

    /**
     * 根据id查询套餐和对应的菜品信息，修改套餐时 回显数据
     *
     * @param id 访问路径：http://localhost:8080/setmeal/1645052884186951682
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> get(@PathVariable Long id) {

        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }
    /**
     * 客户端 根据套餐setmealId，查询套餐和对应的菜品信息，
     * Request URL: http://localhost:8080/setmeal/dish/1648306877658918914
     * Request Method: GET
     * @param id
     * @return

    @GetMapping("/dish/{id}")
    public R<SetmealDto> getSetmealDto(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }*/

    /**
     * 修改菜品
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto) {
//        log.info(dishDto.toString());
        setmealService.updateWithDish(setmealDto);

        return R.success("修改套餐成功");
    }

    /**
     * 根据条件查询套餐数据
     * /setmeal/list ? categoryId=1645021482527604737&status=1
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }

}
